<?php
/**
 * Created by PhpStorm.
 * User: zy-l
 * Date: 2019/6/19
 * Time: 1:23 AM
 */

namespace App\HttpController\Admin;

use App\HttpController\AdminBase;
use App\Model\ActionLog;
use App\Model\AuthGroupAccess;
use App\Model\Config;
use App\Model\Member;
use EasySwoole\Validate\Validate;


class Login extends AdminBase
{


    /**
     * 获取配置文件
     * @return Config
     */
    public function getConfigModel()
    {
        return new Config();
    }

    /**
     * 获取用户模型
     * @return Member
     */
    public function getMemberModel()
    {
        return new Member();
    }

    /**
     * 日志
     * @return ActionLog
     */
    public function getActionLogModel()
    {
        return new ActionLog();
    }

    /**
     * 系统登陆
     */
    public function index()
    {
        if ($this->isPost()) {
            $data = $this->request()->getRequestParam();
            $res = $this->getMemberModel()->login($data);
            $this->session()->set('zy_auth' , $res);
            //数据验证
            return $this->writeJson("操作成功", $res);
        }
        $this->assign(['web_info' => $this->getConfigModel()->getConfigType(['where' => [['type', 2, '=']]])]);
        $this->assign(['checkShow' => $this->getConfigModel()->getConfigKeyName("BACKEND_SWITCH_OTP")]);
        $this->fetch('login');
    }

    /**
     * opt签名验证
     * @return string|void
     */
    public function otp()
    {
        $secret = $this->getMemberModel()->getGoogleSecret();
        $adminUsername = session('lqwsys_member_username');  //登陆用户名
        $qrCodeUrl = "otpauth://totp/" . $adminUsername . "?secret=" . $secret;//生成二维码
        $this->assign("secret", $secret);
        $this->assign("qr_code_url", $qrCodeUrl);
        return $this->fetch("login_otp");
    }

    /**
     * 安全无小事
     * @return mixed
     */
    public function log()
    {
        if ($this->isPost()) {
            $data = $this->request()->getRequestParam();
            return $this->writePageJson("操作成功", $this->getActionLogModel()->getList($data, []));
        }
        return $this->fetch("login_log");
    }

    /**
     * 退出登陆
     * @param Request $request
     * @return array
     */
    public function logout()
    {
        if ($uid = is_login($this->session()->get('zy_auth'))) {
            $this->session()->destroy();
            return $this->writeJson('退出成功',[]);
        } else {
          $this->redirect("/admin/login/index");
        }
    }

    /**
     * 数据验证
     * @param string|null $action
     * @return Validate|null
     */
    protected function getValidateRule(?string $action): ?Validate
    {
        $validate = null;
        if ($this->isPost()) {
            switch ($action) {
                case 'index';
                    $validate = new Validate();
                    $validate->addColumn('username', '登陆账号')->required('不能为空')->lengthMin(4, '长度错误');
                    break;
            }
        }
        return $validate;
    }
}